package morenoapp.components.config2;

import com.jgoodies.binding.adapter.ComboBoxAdapter;
import com.jgoodies.binding.adapter.TextComponentConnector;
import com.jgoodies.binding.beans.PropertyAdapter;
import com.jgoodies.binding.beans.PropertyConnector;
import com.jgoodies.binding.value.AbstractConverter;
import com.jgoodies.binding.value.ConverterFactory;
import com.jgoodies.binding.value.ValueModel;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;
import java.util.Arrays;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import morenoapp.MorenoApp;
import morenoapp.components.common.OfficeColorsComboBox;
import morenoapp.components.help.MorenoHelp;
import morenoapp.model.data.MorenoQuestionFace;
import morenoapp.model.enums.MorenoQuestionType;
import morenoapp.resources.ResourcesHolder;
import morenoapp.util.DocumentedComponent;
import morenoapp.util.EnumFacade;
import morenoapp.util.I18N;
import org.jdesktop.application.Action;

/**
 * Редактор для одного вопроса.
 *
 * @author dmitry.mamonov
 */
@DocumentedComponent
public class QuestionEditorJPanel extends JPanel {
    MorenoQuestionFace question;
    TitledBorder titledBorder;
    JTextField textQuestionMarker;
    JComboBox comboQuestionType;
    JComboBox comboQuestionColor;
    JButton buttonMoveQuestionDown;
    JButton buttonMoveQuestionUp;
    JButton buttonDeleteQuestion;
    JTextArea textQuestionContent;

    public QuestionEditorJPanel(MorenoQuestionFace _question) {
        this.question = _question;
        initComponents();
        initLayout();
    }

    private void initComponents() {
        {
            TitledBorder border = new TitledBorder(new LineBorder(Color.GRAY), "Question"); //NOI18N
            border.setTitlePosition(TitledBorder.TOP);
            ValueModel valueModel = new PropertyAdapter(question, "number");
            valueModel = ConverterFactory.createStringConverter(valueModel, new Format() {
                @Override
                public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
                    return toAppendTo.append(I18N.get("config.question")).append(" ").append(obj);
                }

                @Override
                public Object parseObject(String source, ParsePosition pos) {
                    throw new UnsupportedOperationException("Shoul not happed.");
                }
            });
            PropertyConnector.connectAndUpdate(valueModel, border, "title");
            titledBorder = border;
        }
        {
            JTextField text = new JTextField(3);
            text.setName("textQuestionMarker");
            ValueModel valueModel = new PropertyAdapter(question, "marker");
            TextComponentConnector connector = new TextComponentConnector(valueModel, text);
            connector.updateTextComponent();
            textQuestionMarker = text;
        }
        {
            //binding
            ValueModel valueModel = new PropertyAdapter(question, "type");
            AbstractConverter converter = new AbstractConverter(valueModel) {
                @Override
                public Object convertFromSubject(Object beanValue) {
                    return new EnumFacade(MorenoQuestionType.class, (MorenoQuestionType) beanValue);
                }

                @Override
                public void setValue(Object componentValue) {
                    EnumFacade facade = (EnumFacade) componentValue;
                    subject.setValue(facade.getValue());
                }
            };
            ComboBoxAdapter adapter = new ComboBoxAdapter(EnumFacade.wrapArray(MorenoQuestionType.class, MorenoQuestionType.values()), converter);
            //component
            JComboBox combo = new JComboBox(adapter);
            combo.setName("comboQuestionType");
            comboQuestionType = combo;
        }
        {
            JComboBox combo = new OfficeColorsComboBox();
            combo.setName("comboQuestionColor");

            ValueModel valueModel = new PropertyAdapter(question, "color");
            ComboBoxAdapter adapter = new ComboBoxAdapter(combo.getModel(), valueModel);
            combo.setModel(adapter);

            comboQuestionColor = combo;
        }
        {
            JButton button = new JButton();
            button.setName("buttonMoveQuestionUp");
            button.setText(I18N.get("question_editor.button_move_up"));
            button.setIcon(ResourcesHolder.iconMoveUpSmall);
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    actionMoveQuestionUp();
                }
            });
            button.setEnabled(question.getPrevQuestion()!=null);
            buttonMoveQuestionUp = button;
        }
        {
            JButton button = new JButton();
            button.setName("buttonMoveQuestionDown");
            button.setText(I18N.get("question_editor.button_move_down"));
            button.setIcon(ResourcesHolder.iconMoveDownSmall);
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    actionMoveQuestionDown();
                }
            });
            button.setEnabled(question.getNextQuestion()!=null);
            buttonMoveQuestionDown = button;

        }
        {
            JButton button = new JButton();
            button.setName("buttonDeleteQuestion");
            button.setText(I18N.get("question_editor.button_delete"));
            button.setIcon(ResourcesHolder.iconDeleteSmall);
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    actionDelete();
                }
            });
            buttonDeleteQuestion = button;
        }
        {
            JTextArea text = new JTextArea();
            text.setName("textQuestionContent");
            ValueModel valueModel = new PropertyAdapter(question, "content");
            TextComponentConnector connector = new TextComponentConnector(valueModel, text);
            connector.updateTextComponent();
            textQuestionContent = text;
        }
    }

    private void initLayout() {
        //setup content
        FormLayout layout = new FormLayout(
                //columns
                "p, 1dlu, " + //"label-question-type"
                "p, 7dlu, " + //"question-type"
                "p, 7dlu, " + //"color"
                "p, 1dlu, " + //"marker-label"
                "p, 3dlu, " + //"marker"
                "p, 3dlu, " + //"down"
                "p, 3dlu, " + //"up"
                "p, 3dlu, " + //"delete"
                "p, 0px:grow ", //"help"
                //rows
                "p, 3dlu, " + //header components
                "80px, " + //text field
                "");

        //PanelBuilder builder = new PanelBuilder(layout, new FormDebugPanel()); //debug
        PanelBuilder builder = new PanelBuilder(layout, this);
        //builder.setDefaultDialogBorder();
        builder.setBorder(titledBorder);

        // Obtain a reusable constraints object to place components in the grid.
        CellConstraints cc = new CellConstraints();

        // Fill the grid with components
        int row = 1; //first row
        builder.addLabel(I18N.get("question_editor.question_type_label"), cc.rc(row, 1));
        builder.add(comboQuestionType, cc.rc(row, 3));
        builder.add(comboQuestionColor, cc.rc(row, 5));
        builder.addLabel(I18N.get("question_editor.marker_label"), cc.rc(row, 7));
        builder.add(textQuestionMarker, cc.rc(row, 9));
        builder.add(buttonMoveQuestionUp, cc.rc(row, 11));
        builder.add(buttonMoveQuestionDown, cc.rc(row, 13));
        builder.add(buttonDeleteQuestion, cc.rc(row, 15));
        builder.add(MorenoHelp.createHelpToolbar(this), cc.rc(row, 17));
        row += 2; //next row
        builder.add(new JScrollPane(textQuestionContent), cc.rcw(row, 1, layout.getColumnCount(), "fill, fill"));
        //done
    }

    public MorenoQuestionFace getQuestion() {
        return question;
    }

    @Action
    public void actionDelete() {
        MorenoApp.getApplicationData().getMorenoModelProxy().deleteQuestions(Arrays.asList(question));
    }

    @Action
    public void actionMoveQuestionUp() {
        MorenoApp.getApplicationData().getMorenoModelProxy().moveQuestionUp(question);
    }

    @Action
    public void actionMoveQuestionDown() {
        MorenoApp.getApplicationData().getMorenoModelProxy().moveQuestionDown(question);
    }
}
